package q350;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums1) {
            if (map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int num : nums2) {
            Integer times = map.get(num);
            if (times != null) {
                list.add(num);
                times--;
                if (times==0)
                    map.remove(num);
                else
                    map.put(num, times);
            }
        }
        int[] res = new int[list.size()];
        for(int i = 0; i < list.size() ; i++) {
            res[i] = list.get(i);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums1 = {1,2,2,1}, nums2 = {2,2};
        int[] intersection = (new Solution()).intersect(nums1,nums2);
        System.out.println();
    }
}